package com.study;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginDemo {
    public static void main(String[] args) {
        JFrame jf = new JFrame();
        jf.setDefaultCloseOperation(3);
        jf.setAlwaysOnTop(true);
        jf.setLocationRelativeTo(null);
        jf.setTitle("用户登录");
        jf.setSize(400, 300);
        jf.setLayout(null); // 取消默认布局

        // 显示用户名文本
        JLabel usernameLabel = new JLabel("用户名");
        usernameLabel.setBounds(50, 50, 50, 20);
        jf.add(usernameLabel);

        // 用户名输入框
        JTextField usernameField = new JTextField();
        usernameField.setBounds(150, 50, 180, 20);
        jf.add(usernameField);

        // 显示密码文本
        JLabel passwordLabel = new JLabel("密码");
        passwordLabel.setBounds(50, 100, 50, 20);
        jf.add(passwordLabel);

        // 密码输入框
        JPasswordField passwordField = new JPasswordField();
        passwordField.setBounds(150, 100, 180, 20);
        jf.add(passwordField);

        // 登录按钮
        JButton loginButton = new JButton("登录");
        loginButton.setBounds(50, 200, 280, 20);
        jf.add(loginButton);

        String userName = "lhqoyw";
        String passWord = "250801";

        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 通过输入框对象，获取用户输入的数据
                String userNameStr = usernameField.getText().trim();
                String passWordStr = passwordField.getText().trim();
                // 判断用户名长度
                if (userNameStr.length() < 6 || userNameStr.length() > 12) {
                    JOptionPane.showMessageDialog(jf, "用户名的长度是6-12位，请重新输入！");
                    usernameField.setText("");
                    return;
                }
                // 判断密码长度
                if (passWordStr.length() < 6 || passWordStr.length() > 12) {
                    JOptionPane.showMessageDialog(jf, "密码的长度是6-12位，请重新输入！");
                    passwordField.setText("");
                    return;
                }
                // 如果长度都合法，再判断内容，注意比较字符串的内容，使用equals方法
                if (userNameStr.equals(userName) && passWordStr.equals(passWord)) {
                    JOptionPane.showMessageDialog(jf, "登录成功！");
                    usernameField.setText("");
                    passwordField.setText("");
                } else {
                    JOptionPane.showMessageDialog(jf, "用户名或密码错误！");
                }
            }
        });

        jf.setVisible(true);
    }
}
